var app = getApp();
var api = require('../../config/api.js');
var util = require('../../utils/util.js');
var dataUtil = require('../../utils/data.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    path: "",
    file: "",
    hidden: true,
    file: "",
    qrcode: "",
    placard: '',
    address: "",
    price: "",
    shopName: "",
    shopPhotoUrl: "",
    shopPhoto: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '请稍候',
      mask: true
    })
    var isDownloadImg = false;
    var isDownloadQrcode = false;
    var isDownloadPlacard = false;
    var isDownloadPhoto = false;
    var that = this
    var path = that.data.path;
    var customerId = wx.getStorageSync("customerId");
    var shareId = wx.getStorageSync("shareId");
    var spreadId = wx.getStorageSync("spreadId");
    var type = wx.getStorageSync("type");
    var token = wx.getStorageSync("token");
    if (token == "") {
      wx.showToast({
        title: '请先登录',
      })
      return;
    }
    //如果用户为分销商或者供应商，推荐人id为自己
    if ("1" == type || "0" == type) {
      shareId = customerId;
    } else if ("2" == type) {
      //如果用户为推广人，推广人id传自己id
      spreadId = customerId;
    }
    var shopName = wx.getStorageSync("shopName")
    var shopPhotoUrl = wx.getStorageSync("shopPhoto")

    this.setData({
      path1: options.path,
      goodsId: options.goodsId,
      imgUrl: options.imgUrl,
      file: options.imgUrl,
      goodsName: options.goodsName,
      address: options.address,
      shopName: shopName,
      price: options.price,
      marketPrice: options.marketPrice,
      type: options.type,
      shopPhotoUrl: shopPhotoUrl,
      path: options.path + "?id=" + options.goodsId + "&shareId=" + shareId + "&spreadId=" + customerId + "&shareType=" + options.type,
    })

    if (options.imgUrl.length > 40) {
      //本地图片不需要下载
      wx.downloadFile({
        url: options.imgUrl,
        success: function (res) {
          that.setData({
            file: res.tempFilePath
          })
          isDownloadImg = true;
          console.log("下载商品图片:", res.tempFilePath)
          //  wx.hideLoading()
          if (isDownloadImg && isDownloadQrcode && isDownloadPlacard && isDownloadPhoto) {
            wx.hideLoading();
          }
        }
      })
    }

    wx.downloadFile({
      url: that.data.shopPhotoUrl,
      success: function (res) {
        that.setData({
          shopPhoto: res.tempFilePath
        })
        isDownloadPhoto = true;
        console.log("下载头像图片:", res.tempFilePath)
        //  wx.hideLoading()
        if (isDownloadImg && isDownloadQrcode && isDownloadPlacard && isDownloadPhoto) {
          wx.hideLoading();
        }
      }
    })

    // wx.showLoading({
    //   title: '请稍候',
    // })
    var data = { "path": that.data.path }
    util.request(api.qrcode, data).then(function (res) {
    
      wx.downloadFile({
        url: res,
        success: function (dataimg) {
          that.setData({
            qrcode: dataimg.tempFilePath
          })
          console.log("下载二维码图片:" + dataimg.tempFilePath)
          isDownloadQrcode = true
          if (isDownloadImg && isDownloadQrcode && isDownloadPlacard && isDownloadPhoto) {
            wx.hideLoading();
          }
        }
      })

    })
    var dataPlacard = ""
    if (options.type == 'hotel') {
      dataPlacard = { "type": "PLACARD_HOTEL" }
    } else if (options.type == 'tour') {
      dataPlacard = { "type": "PLACARD_ROUTE" }
    } else {
      dataPlacard = { "type": "PLACARD_SCENE", "goodsId": options.goodsId }
    }
    util.request(api.placard, dataPlacard).then(function (res) {
      wx.downloadFile({
        url: res.datas,
        success: function (dataimg) {
          that.setData({
            placard: dataimg.tempFilePath
          })
          console.log("下载通用背景图片:" + dataimg.tempFilePath)
          isDownloadPlacard = true

          if (isDownloadImg && isDownloadQrcode && isDownloadPlacard && isDownloadPhoto) {
            wx.hideLoading();
          }
        }
      })

    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {




  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    var that = this;
    var path = that.data.path1;
    var customerId = wx.getStorageSync("customerId");
    var shareId = wx.getStorageSync("shareId");
    var spreadId = wx.getStorageSync("spreadId");
    var type = wx.getStorageSync("type");
    var shareType = that.data.type;
    var token = wx.getStorageSync("token");
    if (token == "") {
      wx.showToast({
        title: '请先登录',
      })
      return;
    }
    //如果用户为分销商或者供应商，推荐人id为自己
    if ("1" == type || "0" == type) {
      shareId = customerId;
    } else if ("2" == type) {
      //如果用户为推广人，推广人id传自己id
      spreadId = customerId;
    }

    return {
      title: that.data.goodsName,
      imageUrl: that.data.imgUrl,
      path: path + "?id=" + that.data.goodsId + "&shareId=" + shareId + "&spreadId=" + customerId + "&shareType=" + shareType,
      success: function (res) {
        wx.showToast({
          title: "成功",
          duration: 1000
        });
        setTimeout(function () {
          wx.navigateBack({
          });
        }, 1000)

      },
      fail: function (res) {
        wx.showToast({
          title: '失败',
        })
      }
    }
  },
  share: function () {
    var that = this
    const ctx = wx.createCanvasContext('shareImg')

    //主要就是计算好各个图文的位置
    //1、画出背景图片 
    ctx.drawImage(that.data.placard, 0, 0, 570, 1014)

    //如果是鱼定制产品，则不需要商品图片
    if (that.data.type == "hotel" || that.data.type == "tour") {
      // 2、先取出商品图片
      ctx.drawImage(that.data.file, 0, 0, 570, 683)

      //4、商品名
      ctx.setTextAlign('left')
      ctx.setFillStyle('#000000')
      ctx.setFontSize(30)
      ctx.fillText(that.data.goodsName, 20, 755, 500);

      //7、价格
      ctx.setTextAlign('left')
      ctx.setFillStyle('red')
      ctx.setFontSize(20)
      ctx.fillText("￥", 20, 890)

      ctx.setTextAlign('left')
      ctx.setFillStyle('red')
      ctx.setFontSize(40)
      ctx.fillText(that.data.price, 45, 890)

      if (that.data.marketPrice != null && that.data.marketPrice != "" && that.data.marketPrice != "undefined") {
        ctx.setTextAlign('left')
        ctx.setFillStyle('#A3A3A3')
        ctx.setFontSize(26)
        ctx.fillText("￥" + that.data.marketPrice, 150, 890)
        ctx.rect(150, 882, 100, 2)
        ctx.setFillStyle('#A3A3A3')
        ctx.fill()
      }


      // ctx.setTextAlign('left')
      // ctx.setFillStyle('#000000')
      // ctx.setFontSize(30)
      // ctx.fillText(that.data.address, 39, 934, 530)
    }
    ctx.drawImage("/static/images/shop_bg.png", 10, 30, 405, 55)

    //3、二维码
    console.log("qrcode:" + that.data.qrcode)
    ctx.drawImage(that.data.qrcode, 371, 810, 150, 150)



    // ctx.fillText(that.data.goodsName, 39, 135,430)



    //6、XX店铺
    ctx.setTextAlign('left')
    ctx.setFillStyle('#000000')
    ctx.setFontSize(24)
    ctx.fillText(that.data.shopName + "的店铺", 69, 65)



  // 画头像



    ctx.beginPath(); //开始绘制

    //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
    ctx.arc(38,57, 28, 0, Math.PI*2, false);


    ctx.clip();//画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因

    ctx.drawImage(that.data.shopPhoto, 8, 30, 60, 60); // 推进去图片


   // ctx.draw(); //可将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。
   // ctx.drawImage(that.data.shopPhoto, 14, 30, 50, 50)



    ctx.stroke()
    ctx.draw()
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 570,
      height: 1014,
      destWidth: 570,
      destHeight: 1014,
      canvasId: 'shareImg',
      success: function (datass) {
        console.log(datass.tempFilePath);
        that.setData({
          file: datass.tempFilePath,
          hidden: false
        })

      },
      fail: function (datass) {
        console.log(datass)
      }
    })
  },

  /**
   * 生成海报
  */
  save: function () {
    var that = this;
    //生产环境时 记得这里要加入获取相册授权的代码
    wx.saveImageToPhotosAlbum({
      filePath: that.data.file,
      success(res) {
        wx.showModal({
          content: '海报已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              that.setData({
                hidden: true
              })
              wx.navigateBack({

              })
            }
          }
        })
      }
    })
  },
  close: function () {
    wx.navigateBack({

    })
  }
})